#!/bin/bash

# SPDX-License-Identifier: GPL-2.0-or-later
# Copyright (C) 2017-present Team LibreELEC (https://libreelec.tv)

# compile and copy amlogic autoscript files to part1
mcopy $RELEASE_DIR/3rdparty/bootloader/*autoscript :: 2>&1 > /dev/null || true

# copy device trees to part1
for dtb in $RELEASE_DIR/3rdparty/bootloader/device_trees $RELEASE_DIR/3rdparty/bootloader/*.dtb $RELEASE_DIR/3rdparty/bootloader/dtb.img ; do
  [ -e "$dtb" ] && mcopy -s "$dtb" ::
done

if [ -f "$RELEASE_DIR/3rdparty/bootloader/u-boot" ]; then
  echo "Writing u-boot to $(basename $DISK)"
  dd if="$RELEASE_DIR/3rdparty/bootloader/u-boot" of="$DISK" conv=fsync,notrunc bs=1 count=112 >"$SAVE_ERROR" 2>&1 || show_error
  dd if="$RELEASE_DIR/3rdparty/bootloader/u-boot" of="$DISK" conv=fsync,notrunc bs=512 skip=1 seek=1 >"$SAVE_ERROR" 2>&1 || show_error
fi

if [ -f "$RELEASE_DIR/3rdparty/bootloader/boot.ini" ]; then
  cp -p "$RELEASE_DIR/3rdparty/bootloader/boot.ini" "$LE_TMP/boot.ini"
  sed -e "s/@BOOT_UUID@/$UUID_SYSTEM/" \
      -e "s/@DISK_UUID@/$UUID_STORAGE/" \
      -i "$LE_TMP/boot.ini"
  mcopy "$LE_TMP/boot.ini" ::
fi

if [ -f "$RELEASE_DIR/3rdparty/bootloader/config.ini" ]; then
  mcopy $RELEASE_DIR/3rdparty/bootloader/config.ini ::
fi
